//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package http_custom_api_serv

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/api_common"
	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/api_coll_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/project_entry_dao"
	"atomgit.com/openlinksaas-org/api-server/utils"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/http_custom_api"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_entry_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

type HttpCustomApiImpl struct {
	http_custom_api.UnimplementedHttpCustomApiServer
}

func (apiImpl *HttpCustomApiImpl) CreateCustom(ctx context.Context, req *http_custom_api.CreateCustomRequest) (*http_custom_api.CreateCustomResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &http_custom_api.CreateCustomResponse{
			Code:   http_custom_api.CreateCustomResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	projectItem, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &http_custom_api.CreateCustomResponse{
			Code:   http_custom_api.CreateCustomResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &http_custom_api.CreateCustomResponse{
			Code:   http_custom_api.CreateCustomResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	if projectItem.Closed {
		return &http_custom_api.CreateCustomResponse{
			Code:   http_custom_api.CreateCustomResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	apiCollId := uuid.NewString()

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = api_coll_dao.CustomExtraDao.Insert(sessCtx, &api_coll_dao.CustomExtraInfoDbItem{
			ApiCollId:   apiCollId,
			NetProtocol: req.NetProtocol,
		})
		if err != nil {
			return nil, err
		}
		return &http_custom_api.CreateCustomResponse{
			Code:      http_custom_api.CreateCustomResponse_CODE_OK,
			ApiCollId: apiCollId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*http_custom_api.CreateCustomResponse), nil
}

func (apiImpl *HttpCustomApiImpl) GetCustom(ctx context.Context, req *http_custom_api.GetCustomRequest) (*http_custom_api.GetCustomResponse, error) {
	emptyInfo := &http_custom_api.CustomExtraInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &http_custom_api.GetCustomResponse{
			Code:      http_custom_api.GetCustomResponse_CODE_WRONG_SESSION,
			ErrMsg:    "会话不存在",
			ExtraInfo: emptyInfo,
		}, nil
	}
	_, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &http_custom_api.GetCustomResponse{
			Code:      http_custom_api.GetCustomResponse_CODE_NO_PROJECT,
			ErrMsg:    "项目不存在",
			ExtraInfo: emptyInfo,
		}, nil
	} else if err == utils.ErrNoRole {
		return &http_custom_api.GetCustomResponse{
			Code:      http_custom_api.GetCustomResponse_CODE_NO_PERMISSION,
			ErrMsg:    "没有权限",
			ExtraInfo: emptyInfo,
		}, nil
	} else if err != nil {
		return nil, err
	}

	infoItem, err := api_coll_dao.CustomExtraDao.Get(ctx, req.ApiCollId)
	if err != nil {
		return &http_custom_api.GetCustomResponse{
			Code:      http_custom_api.GetCustomResponse_CODE_NO_CUSTOM_API,
			ErrMsg:    "自定义接口集不存在",
			ExtraInfo: emptyInfo,
		}, nil
	}
	return &http_custom_api.GetCustomResponse{
		Code:      http_custom_api.GetCustomResponse_CODE_OK,
		ExtraInfo: infoItem.ToCustomExtraInfo(),
	}, nil
}

func (apiImpl *HttpCustomApiImpl) UpdateCustom(ctx context.Context, req *http_custom_api.UpdateCustomRequest) (*http_custom_api.UpdateCustomResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &http_custom_api.UpdateCustomResponse{
			Code:   http_custom_api.UpdateCustomResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &http_custom_api.UpdateCustomResponse{
			Code:   http_custom_api.UpdateCustomResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &http_custom_api.UpdateCustomResponse{
			Code:   http_custom_api.UpdateCustomResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}
	if projectItem.Closed {
		return &http_custom_api.UpdateCustomResponse{
			Code:   http_custom_api.UpdateCustomResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	//检查信息是否存在
	entryItem, err := project_entry_dao.EntryDao.Get(ctx, req.ApiCollId, req.ProjectId)
	if err != nil {
		return &http_custom_api.UpdateCustomResponse{
			Code:   http_custom_api.UpdateCustomResponse_CODE_NO_CUSTOM_API,
			ErrMsg: "自定义接口不存在",
		}, nil
	}
	if entryItem.EntryType != uint32(project_entry_api.ENTRY_TYPE_ENTRY_TYPE_API_COLL) {
		return &http_custom_api.UpdateCustomResponse{
			Code:   http_custom_api.UpdateCustomResponse_CODE_NO_CUSTOM_API,
			ErrMsg: "自定义接口不存在",
		}, nil
	}

	hasUpdatePerm := api_common.CheckEntryCanUpdate(sessionItem, projectItem, roleItem, entryItem)

	if !hasUpdatePerm {
		return &http_custom_api.UpdateCustomResponse{
			Code:   http_custom_api.UpdateCustomResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = api_coll_dao.CustomExtraDao.Update(sessCtx, req.ApiCollId, req.NetProtocol)
		if err != nil {
			return nil, err
		}
		return &http_custom_api.UpdateCustomResponse{
			Code: http_custom_api.UpdateCustomResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*http_custom_api.UpdateCustomResponse), nil
}
